# 计算器

from errno import ESRCH
from tkinter import *
from tkinter import messagebox
#  pyinstaller -F manage.py --hidden-import tkinter --noconsole


class Application(Frame):
    """GUI application that manages a simple inventory"""
    def __init__(self, master):
        """Initialize the frame"""
        super(Application, self).__init__(master)
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        """Create widgets to get product information and to display results."""
        self.input_box = Entry(self)
        self.input_box.grid(row=0, column=0,columnspan=4,sticky=EW)
        self.result = Entry(self)
        self.result.config(state='readonly')
        self.result.grid(row=1, column=0,columnspan=4,sticky=EW,)

        btnText = (
            ('AC', '%', '删除', '÷',),
            (7, 8, 9, 'x',),
            (4, 5, 6, '-',),
            (1, 2, 3, '+',),
            (0, '.', '=',)
        )
        for row_num, row_text in enumerate(btnText):
            for col_num, col_text in enumerate(row_text):
                btn = Button(self, text=col_text, width=5)
                btn.config(command=lambda text=col_text: self.add_text(text))
                # if col_text == '0':
                #     btn.grid(row=row_num+2, column=col_num, columnspan=1, sticky=NSEW)
                # if col_text == '.':
                #     btn.grid(row=row_num+2, column=col_num+2,sticky=NSEW)
                if col_text == '=':
                    btn.grid(row=row_num+2, column=col_num,columnspan=2, sticky=NSEW)
                    btn.config(command=lambda: self.calculate())
                if col_text == 'AC':
                    btn.grid(row=row_num+2, column=col_num,sticky=NSEW)
                    btn.config(command=lambda: self.input_box.delete(0, END))

                if col_text == '删除':
                    btn.grid(row=row_num+2, column=col_num,sticky=NSEW)
                    btn.config(command=lambda: self.input_box.delete(len(self.input_box.get())-1))

                else:
                    btn.grid(row=row_num+2, column=col_num,sticky=NSEW)

    def add_text(self, text):
        """Add text to the end of the result entry"""
        current = self.input_box.get()
        self.input_box.delete(0, END)
        self.input_box.insert(0, str(current) + str(text))
        self.input_box.update()

    def calculate(self):
        """Calculate the result and display it"""
        # eval 函数用来计算字符串表达式的值
        content = self.input_box.get()
        result = content.replace('÷', '/').replace('x', '*')
        result = eval(result)
        self.result.config(state='normal')
        self.result.delete(0, END)
        self.result.insert(0, result)
        self.result.update()
        self.result.config(state='readonly')





if __name__ == '__main__':
    root = Tk()
    root.title("小白龙")
    root.geometry("220x200+500+250")
    app = Application(root)
    root.mainloop()
